package com.ellecity06.debugtools.utils

import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.widget.TextView
import androidx.annotation.ColorInt

/**
 * @author ellecity06
 * @time 2023/4/21 15:32
 * @des
 */
internal const val PROMPT: String = "内容大于100kb"
internal fun String?.toJsonStr():String{
    val strJson = this ?: return ""
    // 计数tab的个数
    var tabNum = 0
    val jsonFormat = StringBuffer()
    val length = strJson.length

    var last: Char = 0.toChar()
    for (i in 0 until length) {
        val c = strJson[i]
        if (c == '{') {
            tabNum++
            jsonFormat.append(c + "\n")
            jsonFormat.append(getSpaceOrTab(tabNum))
        } else if (c == '}') {
            tabNum--
            jsonFormat.append("\n")
            jsonFormat.append(getSpaceOrTab(tabNum))
            jsonFormat.append(c)
        } else if (c == ',') {
            jsonFormat.append(c + "\n")
            jsonFormat.append(getSpaceOrTab(tabNum))
        } else if (c == ':') {
            jsonFormat.append("$c ")
        } else if (c == '[') {
            tabNum++
            val next = strJson[i + 1]
            if (next == ']') {
                jsonFormat.append(c)
            } else {
                jsonFormat.append(c + "\n")
                jsonFormat.append(getSpaceOrTab(tabNum))
            }
        } else if (c == ']') {
            tabNum--
            if (last == '[') {
                jsonFormat.append(c)
            } else {
                jsonFormat.append("\n" + getSpaceOrTab(tabNum) + c)
            }
        } else {
            jsonFormat.append(c)
        }
        last = c
    }
    return jsonFormat.toString()
}

/**
 * 设置搜索关键字高亮
 *
 * @param content  原文本内容
 * @param keyword  关键字
 * @param keyColor 高亮颜色
 */
fun TextView.setKeyWordColor(
    content: String?,
    keyword: String?, @ColorInt keyColor: Int,
    countView: TextView? = null
) {

    if (content.isNullOrEmpty() || keyColor == 0) {
        text = ""
        countView?.apply {
            text = ""
        }
        return
    }
    var key = ""
    if (!keyword.isNullOrEmpty()) {
        key = keyword
    } else {
        text = content
        countView?.apply {
            text = ""
        }
        return
    }

    ThreadUtil.queueWork(Runnable {
        val startMillis = System.currentTimeMillis()

        val s = SpannableString(content)
        //Pattern.CASE_INSENSITIVE 不区分大小写
        val contents = content.split(key)
        var index = 0
        if (contents.count() == 1) {
            if (TextUtils.equals(key, content)) {
                s.setSpan(
                    ForegroundColorSpan(keyColor),
                    0,
                    content.count(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        } else {
            for (str in contents) {
                var start = index + str.length
                val end = start + key.length
                if (end > content.length) {
                    continue
                }
                s.setSpan(
                    ForegroundColorSpan(keyColor),
                    start,
                    end,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                index = end
            }
        }

//            val p = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE)
//            val m = p.matcher(s)
//            while (m.find()) {
//                val start = m.start()
//                val end = m.end()
//                s.setSpan(
//                    ForegroundColorSpan(keyColor),
//                    start,
//                    end,
//                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
//                )
//            }
        Log.i("DebugTag", "find 耗时：${System.currentTimeMillis() - startMillis}ms")

        post {
            text = s
            Log.i("DebugTag", "text 耗时：${System.currentTimeMillis() - startMillis}ms")
            countView?.apply {
                if (contents.isNotEmpty()) {
                    text = "搜索结果${contents.size - 1}个"
                } else {
                    text = ""
                }
            }
        }
    })

}
private fun getSpaceOrTab(tabNum: Int): String {
    val sbTab = StringBuffer()
    for (i in 0 until tabNum) {
        sbTab.append('\t')
    }
    return sbTab.toString()
}